package org.dev.`as`.project.main.degrade

import android.content.Context
import android.widget.Toast
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import com.alibaba.android.arouter.facade.template.IInterceptor
import org.dev.`as`.project.common.route.RouteFlag
import org.dev.biz_login.AccountManager
import org.dev.hi.library.util.MainHandler

/**
 * Author WenPing
 * CreateTime 2021/5/11.
 * Description:Y业务的拦截器，判断目标页是否具备预先定义好的属性
 */
class BizInterceptor : IInterceptor {

    private var context: Context? = null


    override fun init(context: Context?) {
        this.context = context
    }

    override fun process(postcard: Postcard?, callback: InterceptorCallback?) {

        val flag = postcard!!.extra
        if ((flag and (RouteFlag.FLAG_LOGIN) != 0)) {
            loginIfNecessary(postcard, callback)
        } else {
            callback!!.onContinue(postcard)
        }
    }

    /**
     * 该方法运行在 arouter的线程池中
     */
    private fun loginIfNecessary(postcard: Postcard, callback: InterceptorCallback?) {
        MainHandler.post(runnable = Runnable {
            Toast.makeText(context,"请先登录",Toast.LENGTH_SHORT).show()
            if (!AccountManager.isLogin()) {
                AccountManager.login(context, Observer { success->
                    callback?.onContinue(postcard)
                })
            } else {
                callback?.onContinue(postcard)
            }
        })
    }
}
